from scrapy import Spider, Request
from urllib.parse import quote
from scrapyseleniumtest.items import ProductItem

class TaobaoSpider(Spider):
    name = 'taobao'
    allowed_domains = ['www.taobao.com']
    start_urls = ['http://www.taobao.com/']
    base_url = 'https://s.taobao.com/search?q='

    def start_requests(self):
        for keyword in self.settings.get('KEYWORDS'):
            for page in range(1,self.settings.get('MAX_PAGE')+1):
                url = self.base_url + quote(keyword)
                yield Request(url,callback=self.parse,meta={page:page}, dont_filter=True)

    def parse(self, response):
        procducts = response.xpath('//div[@id="mainsrp-itemlist"]//div[@class="items"][1]//div[contains(@class, "item")]')
        for procduct in procducts:
            item = ProductItem()
            item['price'] = ''.join(procduct.xpath('.//div[contains(@class,"price")]//text()').extract()).strip()
            item['title'] = ''.join(procduct.xpath('.//div[contains(@class,"title")]//text()').extract()).strip()
            item['shop'] = ''.join(procduct.xpath('.//div[contains(@class,"shop")]//text()').extract()).strip()
            item['image'] = ''.join(procduct.xpath('.//div[contains(@class,"pic")]//img[contains@class,"img"]/@data-src').extract()).strip()
            item['deal'] = procduct.xpath('.//div[contains(@class,"deal-cnt")]//text()').extract_first()
            item['location'] = procduct.xpath('.//div[contains(@class,"location")]//text()').extract_first()
            yield item
